In this example, we are going to show you how to create an HTML table dynamically in ASP.NET using C#.
Create an HTML dynamically in ASP.NET
For many reasons, a developer might need to create a table dynamically. For example, looping through a DataTable in order to print out the rows on the web page requires a table to be created dynamically, as the row number changes based on how many records you have in that DataTable.
The output HTML of the table will be assigned to a literal. So the code of our markup is simply as the following:
<div> <asp:Literal ID="DynamicTable" runat="server"></asp:Literal> </div>
Now import the following namespace to use the string builder class
using System.Text;
And one more to create the DataTable
using System.Data;
Now move to the code behind and add the following code to the Page_Load event
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Department",typeof(string)) }); dt.Rows.Add("Brian", "IT"); dt.Rows.Add("Ed", "Help Desk"); dt.Rows.Add("Peter", "Engineering"); dt.Rows.Add("Scott", "Engineering"); StringBuilder sb = new StringBuilder(); sb.Append("<table cellpadding='3' cellspacing='3' style='border: 1px solid #800000;font-size: 12pt;font-family:Arial'>"); //Add Table Header sb.Append("<tr>"); foreach (DataColumn column in dt.Columns) { sb.Append("<th style='background-color: #3366ff;border: 1px solid #000'>" + column.ColumnName + "</th>"); } sb.Append("</tr>"); //Add Table Rows foreach (DataRow row in dt.Rows) { sb.Append("<tr>"); //Add Table Columns foreach (DataColumn column in dt.Columns) { sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + row[column.ColumnName].ToString() + "</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); DynamicTable.Text = sb.ToString(); } }
Code Explanation
The code above is to create a DataTable and data to it. You can, however, get the data from a database, an API, or from an external file, depending on your requirements.
After the datatable is created and populated with a sample data, we are going to use two for each loop to iterate through the datatable columns and rows, then append the content of the datatable into a string builder variable.
The last step is to assign the value of the string builder variable to the literal.
Run the solution; the output should be something similar to the picture below:
Comments